package com.the_last.controller;

import com.the_last.pojo.bo.LoginUser;
import com.the_last.pojo.dto.ReservationDTO;
import com.the_last.service.ReservationService;
import com.the_last.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/reservation")
public class ReservationController {
    
    @Autowired
    private ReservationService reservationService;
    
    /**
     * 创建预约
     *
     * @param reservationDTO 预约信息
     * @return 预约结果
     */
    @PostMapping("/create")
    @PreAuthorize("hasAuthority('RESERVATION_CREATE')")
    public Result<String> createReservation(
            @RequestBody ReservationDTO reservationDTO,
            @AuthenticationPrincipal LoginUser loginUser) {
        return reservationService.createReservation(reservationDTO, loginUser.getUser().getId());
    }
    
    
    /**
     * 获取预约列表
     *
     * @param venueId  场馆ID（可选）
     * @param date     预约日期（可选，格式：yyyy-MM-dd）
     * @param status   预约状态（可选，-1：全部 0：已取消 1：待使用 2：已使用）
     * @param userId   用户ID（可选）
     * @param pageNum  页码
     * @param pageSize 每页大小
     * @return 预约信息列表
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('RESERVATION_QUERY')")
    public Result getReservationList(
            @RequestParam(required = false) Integer venueId,
            @RequestParam(required = false) String date,
            @RequestParam(defaultValue = "-1") Integer status,
            @RequestParam(required = false) Long userId,
            @RequestParam(defaultValue = "true") Boolean needPaging,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @AuthenticationPrincipal LoginUser loginUser) {
        // 如果不需要分页，校验场地id和日期是否都指定
        if (!needPaging && (venueId == null || date == null)) {
            return Result.fail("不分页查询时，场地ID和日期必须同时指定");
        }
        // 根据权限决定查询范围：具有RESERVATION_QUERY权限的管理员可以查询所有预约，否则只能查询自己的预约
        Long actualUserId = userId;
        if (userId == null && loginUser.getAuthorities().stream()
                .noneMatch(authority -> "ADMIN".equals(authority.getAuthority()))) {
            // 如果没有RESERVATION_QUERY权限且没有指定userId，则只能查询自己的预约
            actualUserId = loginUser.getUser().getId();
        }
        return reservationService.getReservationList(venueId, date, status, actualUserId, needPaging, pageNum, pageSize);
    }
    
    /**
     * 删除预约
     *
     * @param id 预约ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('RESERVATION_DELETE')")
    public Result deleteReservation(@PathVariable Long id) {
        return reservationService.deleteReservation(id);
    }
    
    /**
     * 修改预约状态
     *
     * @param id     预约ID
     * @param status 新状态（0：已取消 1：待使用 2：已使用）
     * @return 修改结果
     */
    @PutMapping("/status")
    @PreAuthorize("hasAuthority('RESERVATION_UPDATE')")
    public Result updateReservationStatus(
            @RequestParam String id,
            @RequestParam Integer status) {
        Long longId = Long.parseLong(id);
        return reservationService.updateReservationStatus(longId, status);
    }
} 